package com.qf.web.controller;

import com.alibaba.fastjson.JSON;
import com.qf.domain.GoodsType;
import com.qf.service.GoodTypeService;
import com.qf.service.impl.GoodTypeServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:jww
 * time:2024/4/16 11:03
 * description:
 */
@WebServlet("/goodstypeservlet")
public class GoodsTypeServlet extends BaseServlet {
    /**
     * AJAX获取商品类别列表
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String goodstypelist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletContext application = this.getServletContext();
        String goodType = (String) application.getAttribute("goodsType");
        if (goodType != null) {
            response.getWriter().write(goodType);
            System.out.println("从application中获取数据");
            return null;
        }
        //创建业务对象
        GoodTypeService goodTypeService=new GoodTypeServiceImpl();
        //调用方法
        List<GoodsType> goodsTypes=goodTypeService.findByLevel(1);
        System.out.println("从数据库中获取数据");
        //把集合转为json字符串
        String json = JSON.toJSONString(goodsTypes);
        //返回json字符串
        response.getWriter().write(json);
        //把json数据存入域对象
        application.setAttribute("goodsType",json);
        return null;
    }

}


